import {
  COMPANY_PRODUCT_LIST,
  CONDITION_TABLE_OF_MAJOR_ENERGY_CONSUMING_EQUIPMENT,
  DETAILED_LIST_OF_COMPANY_INDICATORS,
  ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE,
  ENERGY_CONSUMPTION_STRUCTURE_TABLE,
  ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE, ENTERPRISE_BASIC_INFORMATION_TABLE_ID,
  PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE, TABLE_FIELD_QUARTER, TABLE_FIELD_YEAR,
  TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT, TABLE_REPORTED, TABLE_RESOLVED, TABLE_STAGE
} from '@/config'
import {
  saveOrUpdateCompanyIndicatorDetails,
  saveOrUpdateCompanyProduct,
  saveOrUpdateEnergyConsumptionStructure, saveOrUpdateEnergyConsumptionStructureSchedule,
  saveOrUpdateEquipmentStatus,
  saveOrUpdateGoalCompletionStatus,
  saveOrUpdateProductEnergyConsumption, saveOrUpdateReconstructionProject,
  saveOrUpdateUnitDetails,
} from '@/api/enterpriseQuarterlyReport'
import EnterpriseBasicInformationTable
  from '@/components/quarterly-account-table/enterprise-basic-information-table.vue'
import TableOfComprehensiveEnergyConsumptionPerUnitProduct
  from '@/components/quarterly-account-table/table-of-comprehensive-energy-consumption-per-unit-product.vue'
import EnergySavingRenovationProjectInformationTable
  from '@/components/quarterly-account-table/energy-saving-renovation-project-information-table.vue'
import ProgressEnergySavingTargetCompletionTable
  from '@/components/quarterly-account-table/progress-energy-saving-target-completion-table.vue'
import EnergyConsumptionStructureTable
  from '@/components/quarterly-account-table/energy-consumption-structure-table.vue'
import EnergyConsumptionStructureSubTable
  from '@/components/quarterly-account-table/energy-consumption-structure-sub-table.vue'
import CompanyProductList from '@/components/quarterly-account-table/company-product-list.vue'
import DetailedListOfCompanyIndicators
  from '@/components/quarterly-account-table/detailed-list-of-company-indicators.vue'
import ConditionTableOfMajorEnergyConsumingEquipment
  from '@/components/quarterly-account-table/condition-table-of-major-energy-consuming-equipment.vue'

export default {
  components: {
    EnterpriseBasicInformationTable,
    TableOfComprehensiveEnergyConsumptionPerUnitProduct,
    EnergySavingRenovationProjectInformationTable,
    ProgressEnergySavingTargetCompletionTable,
    EnergyConsumptionStructureTable,
    EnergyConsumptionStructureSubTable,
    CompanyProductList,
    DetailedListOfCompanyIndicators,
    ConditionTableOfMajorEnergyConsumingEquipment,
  },
  data () {
    return {
      // 报表弹框
      showTableAccount: false,
      // 报表只读
      readonly: false,

      // 报表ID
      tableAccountId: null,
      // 报表名称
      tableName: '',
      // 报表列配置
      tableColumns: [],

      // 自动保存填报标识
      useAutoSave: true,
      lastSaveTimestamp: '',

      // 报表状态
      tableStatus: '',
    }
  },
  computed: {
    // 保存报表数据方法
    _save () {
      const tableAccountId = Number(this.tableAccountId)
      let method = null
      switch (tableAccountId) {
        case PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID:
          method = saveOrUpdateGoalCompletionStatus
          break
        case TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.ID:
          method = saveOrUpdateProductEnergyConsumption
          break
        case CONDITION_TABLE_OF_MAJOR_ENERGY_CONSUMING_EQUIPMENT.ID:
          method = saveOrUpdateEquipmentStatus
          break
        case ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.ID:
          method = saveOrUpdateReconstructionProject
          break
        case ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID:
          method = saveOrUpdateEnergyConsumptionStructure
          break
        case COMPANY_PRODUCT_LIST.ID:
          method = saveOrUpdateCompanyProduct
          break
        case DETAILED_LIST_OF_COMPANY_INDICATORS.ID:
          method = saveOrUpdateCompanyIndicatorDetails
          break
        case ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID:
          method = saveOrUpdateEnergyConsumptionStructureSchedule
          break
        case ENTERPRISE_BASIC_INFORMATION_TABLE_ID:
          method = saveOrUpdateUnitDetails
          break
      }
      return method
    },
    // 表ID，tableAccountId 别名
    tId () {
      return this.tableAccountId
    },
    isEnterpriseBasicInformationTable () {
      return Number(this.tId) === ENTERPRISE_BASIC_INFORMATION_TABLE_ID
    },
    isProgressEnergySavingTargetCompletionTable () {
      return Number(this.tId) === PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID
    },
    isTableOfComprehensiveEnergyConsumptionPerUnitProduct () {
      return Number(this.tId) === TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.ID
    },
    isConditionTableOfMajorEnergyConsumingEquipment () {
      return Number(this.tId) === CONDITION_TABLE_OF_MAJOR_ENERGY_CONSUMING_EQUIPMENT.ID
    },
    isEnergySavingRenovationProjectInformationTable () {
      return Number(this.tId) === ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.ID
    },
    isEnergyConsumptionStructureTable () {
      return Number(this.tId) === ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID
    },
    isEnergyConsumptionStructureSubTable () {
      return Number(this.tId) === ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID
    },
    isCompanyProductList () {
      return Number(this.tId) === COMPANY_PRODUCT_LIST.ID
    },
    isDetailedListOfCompanyIndicators () {
      return Number(this.tId) === DETAILED_LIST_OF_COMPANY_INDICATORS.ID
    },
    // 报表组件
    tableComponent () {
      let component = null
      if (this.isEnterpriseBasicInformationTable) {
        component = EnterpriseBasicInformationTable
      } else if (this.isCompanyProductList) {
        component = CompanyProductList
      } else if (this.isTableOfComprehensiveEnergyConsumptionPerUnitProduct) {
        component = TableOfComprehensiveEnergyConsumptionPerUnitProduct
      } else if (this.isDetailedListOfCompanyIndicators) {
        component = DetailedListOfCompanyIndicators
      } else if (this.isProgressEnergySavingTargetCompletionTable) {
        component = ProgressEnergySavingTargetCompletionTable
      } else if (this.isEnergyConsumptionStructureTable) {
        component = EnergyConsumptionStructureTable
      } else if (this.isEnergyConsumptionStructureSubTable) {
        component = EnergyConsumptionStructureSubTable
      } else if (this.isEnergySavingRenovationProjectInformationTable) {
        component = EnergySavingRenovationProjectInformationTable
      } else if (this.isConditionTableOfMajorEnergyConsumingEquipment) {
        component = ConditionTableOfMajorEnergyConsumingEquipment
      }
      return component
    },
    showButton () {
      const status = String(this.tableStatus)
      // 显示暂存/上报/导入按钮的条件
      // 不是 已上报, 也不是 已通过
      return status !== TABLE_REPORTED && status !== TABLE_RESOLVED
    },
    autoSaveAble () {
      return !this.readonly && this.showButton && this.showTableAccount
    }
  },
  beforeDestroy () {
    this.timer && clearInterval(this.timer)
  },
  mounted () {
    this.$nextTick(() => {
      if (this.useAutoSave) {
        // 页面挂载后3s开启自动保存，防止数据还未请求完成
        setTimeout(() => {
          this.autoSave()
        }, 3000)
      }
    })
  },
  methods: {
    // 刷新报表列表
    reload () {
      const enterpriseList = this.enterpriseList
      const isGovernmentSide = enterpriseList && enterpriseList.length > 0
      if (isGovernmentSide) {
        this.enterpriseId = ''
        this.enterprise = ''
      }
      this.$nextTick(() => {
        this.queryLists && this.queryLists()
      })
    },

    /**
     * 返回报表列表页（关闭填报弹框）
     * @param direct{boolean} 为truth时 没有返回弹框提示
     */
    back (direct = false) {
      if (direct) {
        this.showTableAccount = false

        // 刷新
        this.reload()
        return
      }
      this.$confirm('正在填报中，确定要返回吗？').then(() => {
        this.showTableAccount = false
        this.reload()
      }).catch(() => {})
    },

    /**
     * 保存或更新某个报表数据
     * @param state{'2' | '3', '4', '5'}
     * @param illustrate{string}
     * @param keep{boolean}
     */
    saveOrUpdate (state, illustrate = '', keep = false) {
      const data = this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.getData && this.$refs.quarterlyAccountTable.getData()
      const informer = this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.getInformer && this.$refs.quarterlyAccountTable.getInformer()
      const params = {
        [TABLE_FIELD_YEAR]: String(this.year),
        [TABLE_FIELD_QUARTER]: String(this.quarter),
        tenantId: this.enterpriseId,
        ...informer,
      }
      const tId = this.tableAccountId
      if (tId === ENTERPRISE_BASIC_INFORMATION_TABLE_ID) {
        // 企业情况表
        params.data = data.data
        params.list = data.list
      } else {
        params.list = (data || []).map(v => ({
          ...v,
          state: state,
          illustrate: illustrate,
        }))
      }

      if (tId === PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID) {
        // 进度节能目标完成情况表
        // 进度节能量目标完成情况说明
        const description = this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.description
        params.list.push({
          [TABLE_FIELD_YEAR]: String(this.year),
          [TABLE_FIELD_QUARTER]: String(this.quarter),
          projectName: '进度节能量目标完成情况说明',
          oneYear: description ? description.value : ''
        })
      }

      if (
        [
          ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID,
          ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID,
        ].includes(tId)
      ) {
        // 能源结构表和附表
        const summary = this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.summary
        const item = data[0] || {}
        if (summary) {
          params.list.push({
            ...item,
            ...summary.data.reduce((acc, v) => {
              acc[v.key] = String(v.value || '')
              return acc
            }, {}),
            state: state,
          })
        }

        if (tId === ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID) {
          // 本年综合能源消费量（当量值）
          // 上年综合能源消费量（当量值）
          params.consumptionThisYear = this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.currentValue
          params.consumptionLastYear = this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.previousValue
        }
      }

      if (this._save) {
        this._save(params).then(res => {
          this.lastSaveTimestamp = this.$dayjs().format('HH:mm:ss');
          if (!keep) {
            if (res.code === 200) {
              this.$message.success('操作成功')

              // 暂存、上报、通过、驳回后返回（刷新）
              this.back(true)
            }
          }
        })
      }
    },

    /**
     * 填报时自动保存
     * @param s{number} 自动保存时间间隔
     * @param t{string} 自动保存报表的状态 TABLE_STAGE | TABLE_REPORTED，默认为暂存
     */
    autoSave (s = 5, t = TABLE_STAGE) {
      this.timer = setInterval(() => {
        // 如果正在请求数据，则不执行自动保存
        if (this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.loading) {
          console.info('正在请求数据，跳过自动保存')
          return;
        }
        if (this.autoSaveAble) {
          console.info('数据正在自动保存中')
          this.saveOrUpdate(t, '', true)
        }
      }, s * 1000)
    },
    // 暂存报表数据
    saveStage () {
      this.saveOrUpdate(TABLE_STAGE)
    },
    // 上报报表数据
    report () {
      this.timer && clearInterval(this.timer)
      this.saveOrUpdate(TABLE_REPORTED)
    },

    // 加载上期报表数据
    loadPrevData () {
      let year = this.year
      let quarter = this.quarter
      const tenantId = this.enterpriseId || ''
      if (this.$refs.quarterlyAccountTable) {
        if (Number(quarter) === 5) {
          // 年度
          year = Number(year) - 1
        } else {
          quarter = Number(quarter) - 1
          if (quarter === 0) {
            year = Number(year) - 1
            quarter = 4
          }
        }

        this.$refs.quarterlyAccountTable.getPrevLists && this.$refs.quarterlyAccountTable.getPrevLists({
          [TABLE_FIELD_YEAR]: year,
          [TABLE_FIELD_QUARTER]: quarter,
          tenantId: tenantId,
        })
      }
    },
  },
}
